//
//  BrandDisplayDetailVC.m
//  Blank
//
//  Created by whg－54 on 15/9/24.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "BrandDisplayDetailVC.h"
#import "TFHpple.h"
#import "BrandDisDetailTableViewCell.h"
#import "BrandDisplayModel.h"
#import <MJRefresh.h>
#import "AFNetWorkingGet.h"
#import "LocalSave.h"
#import "WatchDetailVC.h"
#import "LocalSave.h"
@interface BrandDisplayDetailVC ()<UITableViewDelegate , UITableViewDataSource>
@property (nonatomic , strong)NSMutableArray *titleArr;
@property (nonatomic , strong)NSMutableArray *markArr;
@property (nonatomic , strong)NSMutableArray *picURLArr;
@property (nonatomic , strong)NSMutableArray *priceArr;
@property (nonatomic , strong)NSMutableArray *popID;
@property (nonatomic , strong)UITableView *brandDetailTableView;
@property (nonatomic , assign)NSInteger loadCount;
@property (nonatomic , strong)WatchDetailVC *watchDetail;

@end

@implementation BrandDisplayDetailVC





#pragma mark - 视图将要出现
- (void) viewWillAppear:(BOOL)animated
{
  
    
    self.navigationController.navigationBar.hidden = NO;
    
    /**
     *  判断夜间模式
     */
    if ([NightModel getColorModel]) {
        self.brandDetailTableView.backgroundColor = [UIColor grayColor];
        [self.brandDetailTableView reloadData];
    }
    else{
        self.brandDetailTableView.backgroundColor = [UIColor whiteColor];
        [self.brandDetailTableView reloadData];
    }


    
    
    
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleArr = [NSMutableArray array];
    self.markArr = [NSMutableArray array];
    self.priceArr = [NSMutableArray array];
    self.picURLArr = [NSMutableArray array];
    self.popID = [NSMutableArray array];
    self.loadCount = 10;
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    buttonBack.frame = CGRectMake(0, 0, 20, 20);
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonBack];
    
    [buttonBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self tableViewSubViews];
    [self setupRefresh];
    
}
#pragma mark - 点击返回
- (void)back:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    
}

#pragma mark - 解析html
- (void) handelHTML:(NSData *)data
{
    TFHpple *xpathParser = [[TFHpple alloc]initWithHTMLData:data];
    NSMutableArray *arr = [xpathParser searchWithXPathQuery:@"//a"].mutableCopy;
    NSMutableArray *arrMark = [xpathParser searchWithXPathQuery:@"//mark"].mutableCopy;
    NSMutableArray *arrPrice = [xpathParser searchWithXPathQuery:@"//span"].mutableCopy;
    NSMutableArray *arrPicURL = [xpathParser searchWithXPathQuery:@"//img"].mutableCopy;
    
    
    for (NSInteger i = 0; i<arr.count; i++) {
        TFHppleElement *hpple = arr[i];
        if (hpple.text != nil && ![hpple.text isEqualToString:@"查看更多..."]) {
            [self.titleArr addObject:hpple.text];
        }else{
            NSDictionary *dic = hpple.attributes;
            if (![[dic objectForKey:@"href"] isEqualToString:@"javascript:getData()"]) {
                NSString *str = [dic objectForKey:@"href"];
                NSArray *divArr = [str componentsSeparatedByString:@":"];
                [self.popID addObject:divArr[2]];
            }
            
            
        }
        
        
    }
    for (NSInteger i = 0; i < arrMark.count; i++) {
        TFHppleElement *hpple = arrMark[i];
        if (hpple.text != nil) {
            [self.markArr addObject:hpple.text];
        }
        
    }
    
    for (NSInteger i = 0; i < arrPrice.count; i++) {
        TFHppleElement *hpple = arrPrice[i];
        if (hpple.text != nil) {
            [self.priceArr addObject:hpple.text];
        }
        
    }
    for (NSInteger i = 0; i < arrPicURL.count; i++) {
        TFHppleElement *hpple = arrPicURL[i];
        NSDictionary *dic = hpple.attributes;
        [self.picURLArr addObject:[dic objectForKey:@"date-src"]];
    }
    
    [self.brandDetailTableView reloadData];
    
    
}


#pragma mark - 设置刷新header和footer
- (void) setupRefresh
{
    self.brandDetailTableView.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    [self.brandDetailTableView.header beginRefreshing];
    
    self.brandDetailTableView.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
#pragma mark - 下拉刷新
- (void) loadNewData
{
    
    self.brandDetailTableView.userInteractionEnabled = NO;
    
    [self.titleArr removeAllObjects];
    [self.picURLArr removeAllObjects];
    [self.priceArr removeAllObjects];
    [self.markArr removeAllObjects];
    [self.popID removeAllObjects];
    
    /**
     *  读取缓存
     */
    if ([LocalSave judgeFileExists:[NSString stringWithFormat:@"brandDDVC%@" , self.brandId]]) {
        NSData *data= [LocalSave readDataFile:[NSString stringWithFormat:@"brandDDVC%@" , self.brandId]];
        [self handelHTML:data];
    }
    else{
        [AFNetWorkingGet popAlertIfNoInter:self];
    }
    
    if ([AFNetWorkingGet IntertReachStatus]) {
        NSLog(@"%@" , self.brandId);
        NSString *str = [NSString stringWithFormat:@BrandDisplayDetailURL, self.brandId];
        NSLog(@"%@" , str);
        NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:str]];
        
        
        NSString *pathName = [NSString stringWithFormat:@"brandDDVC%@" , self.brandId];
        [LocalSave saveFileData:data fileName:pathName];
        [self handelHTML:data];
        [self.brandDetailTableView.header endRefreshing];
        self.brandDetailTableView.userInteractionEnabled = YES;
        
    }
    else{
        [self.brandDetailTableView.header endRefreshing];
        self.brandDetailTableView.userInteractionEnabled = YES;
    }
}


#pragma mark - 上拉加载
- (void) loadMoreData
{
    
    self.brandDetailTableView.userInteractionEnabled = NO;
    NSString *str = [NSString stringWithFormat:@BrandDetailMoreURL , self.brandId , self.loadCount];
    
    //NSLog(@"%ld" , self.loadCount);
    
    [AFNetWorkingGet GETWithAFNByURL:str completion:^(id result) {
        NSDictionary *dic = result;
        if ([dic objectForKey:@"html"] != [NSNull null]
            ) {
            
            NSString *str = [dic objectForKey:@"html"];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            [self handelHTML:data];
            
            [self.brandDetailTableView.footer endRefreshing];
            self.brandDetailTableView.userInteractionEnabled = YES;
            self.loadCount = self.loadCount + 10;
        }
    }];
    
}


#pragma mark - 设置tanleVIew
- (void) tableViewSubViews
{
    self.brandDetailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - self.tabBarController.tabBar.frame.size.height*2) style:UITableViewStylePlain];
    
    self.brandDetailTableView.separatorStyle = 0;
    self.brandDetailTableView.delegate = self;
    self.brandDetailTableView.dataSource = self;
    
    [self.view addSubview:self.brandDetailTableView];
}


#pragma mark - tableView行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArr.count;
}

#pragma mark - tableViewcell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BrandDisDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"brandDetail"];
    if (cell == nil) {
        cell = [[BrandDisDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"brandDetail"];
    }
    BrandDisplayModel *model = [[BrandDisplayModel alloc]init];
    model.titleStr = self.titleArr[indexPath.row];
    model.picUrl = self.picURLArr[indexPath.row];
    model.discribeStr = self.markArr[indexPath.row];
    model.priceStr = self.priceArr[indexPath.row];
    
    cell.model = model;
    
    return cell;
    
    
}

#pragma mark - 点击cell跳转
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

        self.watchDetail = [[WatchDetailVC alloc]init];
        self.watchDetail.popID = self.popID[indexPath.row];
        [self.navigationController pushViewController:self.watchDetail animated:YES];
  
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120*Height;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
